package net.spmiller;

import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.imaging.jpeg.JpegProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.ExifDirectory;
import com.drew.metadata.exif.GpsDirectory;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class FileSystemInterface {
    private static final Logger LOGGER = Logger.getLogger(FileSystemInterface.class);

    public List<FileSystemPhoto> getGeotaggedPhotosFrom(final File directory) {
        if (!directory.isDirectory()) {
            throw new IllegalArgumentException("The passed file is not a directory: " + directory);
        }

        final List<FileSystemPhoto> photos = new ArrayList<FileSystemPhoto>();
        final Collection<File> files = FileUtils.listFiles(directory, new String[]{"jpg", "JPG"}, true);
        for (File jpegFile : files) {
            if (jpegFile.getParentFile().isHidden()) {
                continue;
            }
            final Metadata metadata;
            try {
                metadata = JpegMetadataReader.readMetadata(jpegFile);
            } catch (JpegProcessingException e) {
                LOGGER.error("Problem processing file '" + jpegFile + "'", e);
                continue;
            }
            final Directory exifDirectory = metadata.getDirectory(ExifDirectory.class);
            final String uniqueId = exifDirectory.getString(ExifDirectory.TAG_IMAGE_UNIQUE_ID);
            if (StringUtils.isNotEmpty(uniqueId)) {
                final Directory gpsDirectory = metadata.getDirectory(GpsDirectory.class);
                final String latitude = gpsDirectory.getString(GpsDirectory.TAG_GPS_LATITUDE);
                final String longitude = gpsDirectory.getString(GpsDirectory.TAG_GPS_LONGITUDE);
                final String gpsVersion = gpsDirectory.getString(GpsDirectory.TAG_GPS_VERSION_ID);


                photos.add(new FileSystemPhoto(jpegFile.getAbsolutePath(), uniqueId, new Location(latitude, longitude, gpsVersion)));
            }
        }
        return photos;
    }
}
